package com.zyy.joseata.mq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.Collection;

/**
 * 只能在SimpleMessageListenerContainer下拦截,  目前在command中拦截成功. (SimpleMessageListenerContainer, ChannelAwareMessageListener) 手动处理中拦截成功
 * @author zhangyy
 */
//@Slf4j
////@ConditionalOnClass(SimpleMessageListenerContainer.class)
////@Component
//public class JoSeataSmartFromProcessorConfig  implements SmartInitializingSingleton {
//
//    @Autowired(required = false)
//    SimpleMessageListenerContainer listenerContainer;
//
//    @Override
//    public void afterSingletonsInstantiated() {
//        if (listenerContainer != null) {
//            setAfterReceivePostProcessors(listenerContainer);
//        }
//    }
//
//
//    public void setAfterReceivePostProcessors(SimpleMessageListenerContainer listenerContainer) {
//        try {
//            Class<?> obj = Class.forName("org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer");
//            Field field = obj.getSuperclass().getDeclaredField("afterReceivePostProcessors");
//            field.setAccessible(true);
//            Collection<MessagePostProcessor> messagePostProcessors = (Collection<MessagePostProcessor>)field.get(listenerContainer);
//            if (CollectionUtils.isEmpty(messagePostProcessors)) {
//                listenerContainer.setAfterReceivePostProcessors(new JoSeataMqListenerMessageProcess());
//            }else {
//                messagePostProcessors.add(new JoSeataMqListenerMessageProcess());
//            }
//            log.info("Initial tracingFromMessagePostProcessor success.");
//        } catch (Exception e) {
//            log.error("Initial tracingFromMessagePostProcessor failed.", e);
//        }
//    }
//}
